﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ILogger = FDFtpSync.Core.ILogger;

namespace FDFtpSync.Entities
{
    /*
     * CreatedOn: 2018-05-23
     * CreatedBy: Jackie Lee(天宇遊龍)
     */
    /// <summary>
    /// 默认日志
    /// </summary>
    public class DefaultLogger : ILogger
    {
        private string logDir = "logs";
        private string fileName => $"{logDir}/{DateTime.Now.ToString("yyyyMMdd")}.log";

        public DefaultLogger()
        {
            if (!Directory.Exists(logDir))
            {
                Directory.CreateDirectory(logDir);
            }
        }

        public void Info(string msg)
        {
            Log("INFO", msg);
        }

        public void Error(string msg, Exception ex = null)
        {
            Log("ERROR", msg, ex);
        }

        private static object _sync = new object();
        private void Log(string tip, string msg, Exception ex = null)
        {
            msg = $"[{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}] {tip} {msg}\r\n";
            if (ex != null)
            {
                msg = $"{msg}{ex.Message}\r\n{ex.Source}\r\n{ex.StackTrace}\r\n";
            }

            Console.Write(msg);
            lock (_sync)
            {
                File.AppendAllText(fileName, msg, Encoding.UTF8);
            }
        }
    }
}
